import { queryOrder } from "../api";
import { Toast } from "vant";
import { jumpTool } from "@xiaoe/h5-jump-fe";
import { clearOrderCache } from "../utils/index";

//支付回调
export class PayBackHandler {
  constructor(paySuccessUrl, payFailUrl, order) {
    this.paySuccessUrl = paySuccessUrl;
    this.payFailUrl = payFailUrl;
    this.order = order;
  }
  perform(failCallBack = () => {}) {
    const { trade_id, order_id } = this.order;
    const params = {
      trade_id,
      order_id,
    };
    queryOrder(params)
      .then((data) => {
        // clearOrderCache();
        const payOrderState = data.info.pay_state;
        if (payOrderState === "SUCCESS") {
          setTimeout(() => {
            jumpTool.jumpTargetUrl({
              url: decodeURIComponent(this.paySuccessUrl),
              isReplace: true,
            });
          }, 800);
        } else {
          return Promise.reject(data);
        }
      })
      .catch((err) => {
        const abortedMsg = sessionStorage.getItem('abortedMsg');
        Toast(abortedMsg || "您的订单未完成支付");
        const currentUrl = location.href;
        if (currentUrl == this.payFailUrl) {
          failCallBack();
        } else {
          jumpTool.jumpTargetUrl({
            url: decodeURIComponent(this.payFailUrl),
            isReplace: true,
          });
        }
      });
  }
}
